import { useEffect } from 'react';
import {
  Form,
  Input,
  DatePicker,
  Select,
  Button,
  Space,
  message,
  Row,
  Col,
  Alert,
} from 'antd';
import {
  SaveOutlined,
  CloseOutlined,
} from '@ant-design/icons';
import useMembersStore from '../../store/members/useMembersStore';
import { MEMBER_LEVELS, getLevelByPoints } from '../../constants/memberLevels';
import dayjs from 'dayjs';

const { Option } = Select;

const MemberForm = ({ member, onSuccess, onCancel }) => {
  const [form] = Form.useForm();
  const { updateMember } = useMembersStore();

  useEffect(() => {
    if (member) {
      form.setFieldsValue({
        nickname: member.nickname,
        phone: member.phone,
        birthday: member.birthday ? dayjs(member.birthday) : null,
        level: member.level,
        points: member.points,
        wechat: member.wechat,
      });
    }
  }, [member, form]);

  const handleSubmit = async (values) => {
    try {
      const autoLevel = getLevelByPoints(values.points);
      
      const formData = {
        ...values,
        birthday: values.birthday ? values.birthday.format('YYYY-MM-DD') : null,
        level: autoLevel.value,
      };

      await updateMember(member.id, formData);
      message.success('会员信息更新成功');
      onSuccess?.();
    } catch {
      message.error('更新失败');
    }
  };

  const currentPoints = Form.useWatch('points', form);
  const suggestedLevel = currentPoints ? getLevelByPoints(currentPoints) : null;

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      autoComplete="off"
    >
      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="会员昵称"
            name="nickname"
            rules={[
              { required: true, message: '请输入会员昵称' },
              { max: 20, message: '昵称最多20个字符' }
            ]}
          >
            <Input placeholder="请输入会员昵称" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="手机号"
            name="phone"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={12}>
          <Form.Item
            label="生日"
            name="birthday"
          >
            <DatePicker
              format="YYYY-MM-DD"
              style={{ width: '100%' }}
              placeholder="选择生日"
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label="微信号"
            name="wechat"
          >
            <Input placeholder="请输入微信号" />
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16}>
        <Col span={24}>
          <Form.Item
            label="会员积分"
            name="points"
            rules={[{ required: true, message: '请输入会员积分' }]}
          >
            <Input type="number" placeholder="请输入会员积分" />
          </Form.Item>
          {suggestedLevel && (
            <Alert
              message={`根据积分 ${currentPoints}，会员等级将自动设置为：${suggestedLevel.label} (${suggestedLevel.minPoints}-${suggestedLevel.maxPoints === Infinity ? '∞' : suggestedLevel.maxPoints} 积分)`}
              type="info"
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}
        </Col>
      </Row>

      <Form.Item>
        <Space>
          <Button
            type="primary"
            htmlType="submit"
            icon={<SaveOutlined />}
          >
            保存修改
          </Button>
          <Button
            onClick={onCancel}
            icon={<CloseOutlined />}
          >
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default MemberForm;
